/*
	This file is part of BGO External Jukebox.

	BGO External Jukebox is free software:
	you can redistribute it and/or modify it under the terms
	of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License,
	or (at your option) any later version.

	BGO External Jukebox is distributed  in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
	or FITNESS FOR A PARTICULAR PURPOSE.

	See the GNU General Public License for more details.

	You should have received a copy of the GNU General Public License  along with
	BGO External Jukebox. If not, see <http://www.gnu.org/licenses/>.
*/

// bgo's servers starts with {s[Number]}.boardgame-online.com
var subdomain = location.hostname.split('.')[0];

if (subdomain[0] == 's')
{
	/* begin, from http://myjs.us/param.js */
	function ptq(q)
	{
		/* parse the query */
		/* semicolons are nonstandard but we accept them */
		var x = q.replace(/;/g, '&').split('&'), i, name, t;
		/* q changes from string version of query to object */
		for (q={}, i=0; i<x.length; i++)
		{
			t = x[i].split('=', 2);
			name = unescape(t[0]);
			if (!q[name])
				q[name] = [];
			if (t.length > 1)
			{
				q[name][q[name].length] = unescape(t[1]);
			}
			/* next two lines are nonstandard */
			else
				q[name][q[name].length] = true;
		}
		return q;
	}
	/* end, from http://myjs.us/param.js */

	function jukeboxParam(url) {
		var query = url.indexOf('?');

		if (query != -1)
		{
			url = url.substring(query);
			return ptq(url.substring(1).replace(/\+/g, ' '));
		}

		return undefined;
	}

	var _bgo_j_counter = 0;

	var _bgo_j = new Array();
	_bgo_j['jukebox'] = null;
	_bgo_j['header'] = null;
	_bgo_j['jukebox_ready'] = false;

	var _bgo_j_max = Object.keys(_bgo_j).length;

	function _getSettings(callback)
	{
		if (typeof _getSettings.message === 'undefined')
		{
			_getSettings.message = {settings: true};
		}

		chrome.extension.sendMessage(_getSettings.message, callback);
	}

	function _updateJukebox(url)
	{
		if (typeof _updateJukebox.message === 'undefined')
		{
			_updateJukebox.message = {jukebox: url};
		}
		else
		{
			_updateJukebox.message.jukebox = url;
		}

		chrome.extension.sendMessage(_updateJukebox.message);
	}

	function _closeJukebox()
	{
		if (typeof _closeJukebox.message === 'undefined')
		{
			_closeJukebox.message = {close: true};
		}

		chrome.extension.sendMessage(_closeJukebox.message);
	}

	function onJukeboxStateChanged_updateVideo(settings)
	{
		if (settings['_bgo_detach_jukebox'] == 1)
		{
			_bgo_j['jukebox'].stopVideo();
			var url = jukeboxParam(_bgo_j['jukebox'].getVideoUrl())['v'];

			if (typeof(url) !== 'undefined')
			{
				_updateJukebox(url[0]);
			}
			else
			{
				_closeJukebox();
			}
		}
		else
		{
			_closeJukebox();
		}
	}

	function onJukeboxStateChanged(state)
	{
		if (state == 1 || state == 2 || state == 3)
		{
			_getSettings(onJukeboxStateChanged_updateVideo);
		}
	}

	function onJukeboxMessage(event)
	{
		if (event.source != window)
		{
			return;
		}

		if (event.data.type == 'BGO_JUKEBOX_STATE')
		{
			onJukeboxStateChanged(event.data.text);
		}
	}

	var $jukeboxHook = undefined;
	function jukeboxHook(summary)
	{
		if (!_bgo_j['header'] && (_bgo_j['header'] = document.getElementById('jukebox_header')))
		{
			_bgo_j_counter++;

			var closeBtn = document.createElement('a');
			closeBtn.id = '_bgo_jukebox_closeyt';
			closeBtn.className = 'headerButton linkButton';
			closeBtn.style.backgroundImage = "url('" + chrome.extension.getURL('cross.png') + "')";
			closeBtn.addEventListener('click', _closeJukebox);
			document.getElementById('jukebox_header').appendChild(closeBtn);
		}

		if (!_bgo_j['jukebox'] && (_bgo_j['jukebox'] = document.getElementById('jukebox_YouTubePlayer')))
		{
			_bgo_j_counter++;
		}

		if (_bgo_j['jukebox'] && !_bgo_j['jukebox_ready'])
		{
			if (typeof _bgo_j['jukebox'].getVideoUrl !== 'undefined')
			{
				_bgo_j_counter++;
				_bgo_j['jukebox_ready'] = true;

				window.addEventListener('message', onJukeboxMessage);

				var callback = document.createElement('script');
				callback.innerHTML = "_bgo_yt=document.getElementById('jukebox_YouTubePlayer');_bgo_ytmsg={type:'BGO_JUKEBOX_STATE'};function _bgo_ytsc(){_bgo_ytmsg.text=_bgo_yt.getPlayerState();window.postMessage(_bgo_ytmsg, '*');}_bgo_yt.addEventListener('onStateChange','_bgo_ytsc');";
				document.body.appendChild(callback);
			}
			else
			{
				setTimeout(jukeboxHook, 1000);
			}
		}

		if (_bgo_j_counter == _bgo_j_max)
		{
			$jukeboxHook.mutationSummary('disconnect');
		}
	}

	$jukeboxHook = $('#jukeboxElement');

	$jukeboxHook.mutationSummary('connect', jukeboxHook, [{
		element: '#jukebox_toggleButton',
		elementAttributes: 'class'
	}]);

	jukeboxHook();
}
